export class RNG {

    static rand(min: number, max: number, func: (t: number) => number = t => t) {
        return func(Math.random()) * (max - min) + min;
    }
    static arrRand<T>(a: Array<T>) {
        if (!a || a.length == 0)
            return null;
        return a[Math.floor(Math.random() * a.length)];
    }
    static weiRand<T>(wei: number[], element: T[]) {
        if (wei.length != element.length) {
            console.error("概率数组和元素数组不匹配");
            return;
        }
        let probCnt = 0;
        let rand = Math.random();
        let allWei = 0;
        wei.forEach(e => allWei += e);
        for (let i = 0; i < wei.length; i++) {
            let e = element[i];
            let p = wei[i] / allWei;
            if (rand <= probCnt + p)
                return e;
            probCnt += p;
        }
        return element[element.length - 1];
    }
    /**wei:权重数组，element:元素数组，isRepeat:是否放回 */
    static weiRandMul<T>(wei: number[], element: T[], m: number, isRepeat: boolean) {
        let w = [...wei];
        let e = [...element];
        let res: T[] = [];
        for (let i = 0; i < m; i++) {
            if (w.length == 0)
                return;
            let r = this.weiRand(w, e);
            if (!isRepeat) {
                let idx = e.indexOf(r);
                w.splice(idx, 1);
                e.splice(idx, 1);
            }
            res.push(r);
        }
        return res;
    }
}